//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI

class WeeklyLetterParam : Identifiable {
    let id = UUID()
    var items: WeeklyLetterBean? = nil
    var title: String = ""
}

//每周来信
class WeeklyLetterViewModel : BaseViewModel {
    @Published var items = [WeeklyLetterParam]()
    @Published var status = ""
    private var mapTitle : [String:Bool] = [:]

    func getData(_ isRefresh: Bool = false) {
        var isMore = false
        requestList(isRefresh: isRefresh) {
            var listAll: [WeeklyLetterParam] = []
            let list = try await BackupsManager.shared.getDelegateDiary()?.queryWeekLetter(
                userId: userManager.getUserId(),
                pageNo: self.pageNo,
                pageSize: self.pageSize
            ) ?? []
            for bean in list {
                let role = try await DiaryExt.getRole(bean)
                if role != nil {
                    bean.name = role?.name
                    bean.avatar = role?.avatar
                }
            }
            isMore = list.count < self.pageSize
            //将同年处理为一个字典
            let grouped = Dictionary(grouping: list) { bean -> String in
                return TimeUtils.getDate(time: bean.time, format: "yyyy")
            }
            grouped.forEach {
                let title = $0.key
                let value = $0.value
                if !self.mapTitle.keys.contains(title) && title != TimeUtils.getDate(time: getNetTimeLocal(), format: "yyyy") {
                    let param = WeeklyLetterParam()
                    param.title = title
                    listAll.append(param)
                    self.mapTitle[title] = true
                }
                value.forEach {
                    let param = WeeklyLetterParam()
                    param.items = $0
                    listAll.append(param)
                }
            }
            try check(!isRefresh || !list.isEmpty, "暂无来信📨")
            return listAll
        } noMore: { list in
            return isMore
        } suc: { listAll in
            self.status = ""
            self.items.append(contentsOf: listAll)
        } fail: {
            self.status = $0.message
        }
    }
    
    func doRead(read : Binding<Bool>, bean: Binding<WeeklyLetterBean>) {
        if read.wrappedValue {
            return
        }
        request(isLoading: false) {
            read.wrappedValue = true
            bean.read.wrappedValue = true
            try await BackupsManager.shared.getDelegateDiary()?.updateLastWeekLetter(bean: bean.wrappedValue)
        } suc: { _ in
        } fail: {
            showToast($0.message)
        }
    }
    
    func doRead(bean: WeeklyLetterBean) {
        request(isLoading: false) {
            bean.read = true
            _ = try await BackupsManager.shared.getDelegateDiary()?.updateLastWeekLetter(bean: bean)
        } suc: { _ in
        } fail: {
            showToast($0.message)
        }
    }
    
    func doDel(index: Int, bean: WeeklyLetterBean,sucResult: @escaping ()-> Void) {
        request {
            try await BackupsManager.shared.getDelegateDiary()?.deleteLastWeekLetter(bean: bean)
        } suc: { _ in
            sucResult()
        } fail: {
            showToast($0.message)
        }
    }
    
    //用户补发来信读取
    func reissueLetterRead() {
        request {
            userManager.user?.extraConfig?.reissueLetter = nil

            try await retry(maxRetries: 5, retryDelayMillis: 500) {
                if let user = userManager.user {
                    try await LeancloudManager.instance.save(todo: user)
                    userManager.update()
                }
            }
        } suc: { _ in
        } fail: { _ in

        }
    }
}
